package com.zenika.zenbinding.client.handler;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.SourcesTableEvents;
import com.google.gwt.user.client.ui.TableListener;
import com.google.gwt.user.client.ui.Widget;
import com.zenika.zenbinding.client.model.TableModel;

public class FlexTableHandler extends TableBindingHandler implements TableListener {

	private FlexTable table;
	private TableModel model;

	public FlexTableHandler(FlexTable table, TableModel model) {
		super();
		this.table = table;
		table.addTableListener(this);
		this.model = model;
		this.model.setHandler(this);
		this.bind();
	}

	public void bind() {
		int rowCount = this.model.getRowCount();
		int columnCount = this.model.getColumnCount();
		if (this.model.hasHeaders()) {
			for (int column = 0; column < columnCount; column++) {
				this.table.setWidget(0, column, this.model.getHeader(column));
			}
		}
		for (int row = 0; row < rowCount; row++) {
			for (int column = 0; column < columnCount; column++) {
				this.table.setWidget((this.model.hasHeaders()) ? row + 1 : row, column, this.model.getCellModel(row,
						column).getView(this));
			}
		}
	}

	public void onCellClicked(SourcesTableEvents sender, int row, int column) {
		this.fireOnClick((this.model.hasHeaders()) ? row - 1 : row, column);
	}

	public void setErrorStyle() {
		this.table.setStyleName("error-FlexTable");
	}

	public void setRegularStyle() {
		this.table.setStyleName("gwt-FlexTable");
	}

	public Widget getWidget() {
		return this.table;
	}

	public Object getValue() {
		// FIXME don't do anything, the signature should be changed, etc
		return null;
	}

}
